﻿using AutoMapper;
using Blog.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RxxApi.Common.Helper;
using RxxApi.Extensions.Authorizations;
using RxxApi.IServices.System;
using RxxApi.Model;
using RxxApi.Services.System;

namespace RxxApi.Api.Controllers.System;
/// <summary>
/// 用户管理
/// </summary>
public class SysUserController : BaseApiController
{
    private readonly ISysUserServices _sysUserServices;
    private readonly IMapper _mapper;

    public SysUserController(ISysUserServices sysUserServices, IMapper mapper)
    {
        _sysUserServices = sysUserServices;
        _mapper = mapper;
    }
    /// <summary>
    /// 获取JWT的方法1
    /// </summary>
    /// <param name="name"></param>
    /// <param name="pass"></param>
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public async Task<MessageModel<string>> GetJwtStr(string name, string pass)
    {
        string jwtStr = string.Empty;
        bool suc = false;
        //这里就是用户登录以后，通过数据库去调取数据，分配权限的操作
        var user = await _sysUserServices.GetUserInfo(name, MD5Helper.MD5Encrypt32(pass));
        if (user != null)
        {
            TokenModelJwt tokenModel = new TokenModelJwt { Uid = user.Id };
            jwtStr = JwtHelper.IssueJwt(tokenModel);
            suc = true;
        }
        else
        {
            jwtStr = "login fail!!!";
        }
        return new MessageModel<string>()
        {
            success = suc,
            msg = suc ? "获取成功" : "获取失败",
            response = jwtStr
        };
    }
    /// <summary>
    /// 根据Token获取用户信息
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public async Task<MessageModel<SysUserDto>> GetUserInfoByToken(string token)
    {
        var data = new MessageModel<SysUserDto>();
        if (!string.IsNullOrEmpty(token))
        {
            var tokenModel = JwtHelper.SerializeJwt(token);
            if (tokenModel != null && tokenModel.Uid > 0)
            {
                var userinfo = await _sysUserServices.QueryById(tokenModel.Uid);
                if (userinfo != null)
                {
                    data.response = _mapper.Map<SysUserDto>(userinfo);
                    data.success = true;
                    data.msg = "获取成功";
                }
            }
        }

        return data;
    }
}
